package com.wwwarehouse.carddesk.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.carddesk.R;
import com.wwwarehouse.carddesk.adapter.FunctionDetailsAdapter;
import com.wwwarehouse.carddesk.constant.CardDeskConstant;
import com.wwwarehouse.carddesk.utils.TaskRouterUtils;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CardDeskFunctionResponseBean;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.constant.Constant;
import com.wwwarehouse.common.custom_widget.popupwindow.EasyPopupWindow;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.ConvertUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ScreenUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static com.wwwarehouse.carddesk.fragment.FunctionTabFragment.KEY_FUNCTION_BU_ID;
import static com.wwwarehouse.carddesk.fragment.FunctionTabFragment.KEY_FUNCTION_ORDER_SORT;
import static com.wwwarehouse.carddesk.fragment.FunctionTabFragment.KEY_FUNCTION_ORDER_TYPE;
import static com.wwwarehouse.carddesk.fragment.FunctionTabFragment.KEY_FUNCTION_PAGE;
import static com.wwwarehouse.carddesk.fragment.FunctionTabFragment.KEY_FUNCTION_SEARCH_TEXT;
import static com.wwwarehouse.carddesk.fragment.FunctionTabFragment.KEY_FUNCTION_TAG_SET;
import static com.wwwarehouse.carddesk.fragment.FunctionTabFragment.LIMIT;

/**
 * Created by Jackie on 2017/8/17.
 * 卡片桌面功能卡片
 */

public class FunctionDetailsFragment extends BaseFragment implements View.OnClickListener, EasyPopupWindow.ChildClickListener  {
    private View mRootView;
    private StateLayout mStateLayout;
    private GridView mGridView;
    private FunctionDetailsAdapter mAdapter;

    private EasyPopupWindow mEasyPopupWindow;

    private String mBuId;
    private String mOrderSort;
    private String mOrderType;
    private String mSearchText;
    private Set<String> mTaskTagSet;
    private int mPage = 0;

    private CardDeskFunctionResponseBean.TaskBean mTaskDetailsBean;

    private String mType;

    private static final int REQUEST_GET_FUNCTION_INFO = 0;
    private static final int REQUEST_OPERATION_FAVORITE = 1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView = inflater.inflate(R.layout.fragment_function_details, container, false);
        return mRootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initView();
        initEvent();
    }

    @Override
    public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
        if (enter) {
            getFunctionInfo();
        }

        return null;
    }

    private void initView() {
        mStateLayout = findView(mRootView, R.id.sl_layout);
        mGridView = findView(mRootView, R.id.gv_details);

        Bundle bundle = getArguments();
        if (bundle != null) {
            mBuId = bundle.getString(KEY_FUNCTION_BU_ID);
            mOrderSort = bundle.getString(KEY_FUNCTION_ORDER_SORT);
            mOrderType = bundle.getString(KEY_FUNCTION_ORDER_TYPE);
            mSearchText = bundle.getString(KEY_FUNCTION_SEARCH_TEXT);
            mTaskTagSet = (Set<String>) bundle.getSerializable(KEY_FUNCTION_TAG_SET);
            mPage = bundle.getInt(KEY_FUNCTION_PAGE);
        }
    }

    private void initEvent() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        if (id == R.id.btn_favorite) {
            showProgressDialog(getString(R.string.loading));

            //收藏
            favoriteOperation("F");
        } else if (id == R.id.btn_cancel) {

        }

        if (mEasyPopupWindow != null && mEasyPopupWindow.isShowing()) {
            mEasyPopupWindow.dismiss();
        }
    }

    @Override
    public void getChildView(int layoutId, View view) {
        Button favorite = (Button) view.findViewById(R.id.btn_favorite);
        Button cancel = (Button) view.findViewById(R.id.btn_cancel);

        favorite.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    @Override
    public void setTitle() {

    }

    @Override
    public void requestDatas() {

    }

    private void getFunctionInfo() {
        mStateLayout.showProgressView(false);

        Map map = new HashMap<>();

        map.put("actionType", "C");

        if (!TextUtils.isEmpty(mBuId)) {
            map.put("buId", mBuId);
        }

        map.put("limit", LIMIT);
        map.put("page", mPage);
        map.put("orderSort", mOrderSort);
        map.put("orderType", mOrderType);
        map.put("searchText", mSearchText);
        map.put("taskTags", mTaskTagSet);

        NoHttpUtils.httpPost(CardDeskConstant.URL_GET_FUNCTION_INFO, map, mOnResponseListener, REQUEST_GET_FUNCTION_INFO);
    }

    /**
     * 收藏或点击
     */
    private void favoriteOperation(String type) {
        mType = type;

        Map map = new HashMap();

        map.put("cardUnitUkid", mTaskDetailsBean.getTaskTypeUkid());
        map.put("favType", type);
        map.put("userId", sp.getValue(Constant.sp_User_Id));

        NoHttpUtils.httpPost(CardDeskConstant.URL_OPERATION_FAVORITE, map, mOnResponseListener, REQUEST_OPERATION_FAVORITE);
    }

    NoHttpUtils.OnResponseListener mOnResponseListener = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int what) {
            switch (what) {
                case REQUEST_GET_FUNCTION_INFO:
                    if ("0".equals(commonClass.getCode())) {
                        CardDeskFunctionResponseBean cardDeskFunctionResponseBean = JSON.parseObject(commonClass.getData().toString(), CardDeskFunctionResponseBean.class);
                        final List<CardDeskFunctionResponseBean.BusinessBean> businessDetailsList = cardDeskFunctionResponseBean.getBuIds();
                        final List<CardDeskFunctionResponseBean.TaskBean> taskDetailsList = cardDeskFunctionResponseBean.getTasks();

                        int screenHeight = ScreenUtils.getScreenHeight(mActivity);
                        int statusHeight = ScreenUtils.getStatusHeight(mActivity);

                        int itemHeight = (screenHeight - statusHeight - ConvertUtils.dip2px(mActivity, 132)) / 5;

                        mAdapter = new FunctionDetailsAdapter(mActivity, taskDetailsList, itemHeight);
                        mGridView.setAdapter(mAdapter);

                        mGridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
                            @Override
                            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                                mTaskDetailsBean = taskDetailsList.get(position);

                                if ("1".equals(mTaskDetailsBean.getIsCollect())) {
                                    toast(getString(R.string.favorite_done));
                                } else {
                                    mEasyPopupWindow = PopUpUtils.showPopUpBottom(R.layout.function_favorite_popupwindow, mActivity, mActivity.findViewById(android.R.id.content), true, FunctionDetailsFragment.this);
                                }

                                return true;
                            }
                        });

                        //所有卡片的跳转事件
                        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                mTaskDetailsBean = taskDetailsList.get(position);

                                // new
                                if ("1".equals(mTaskDetailsBean.getIsClick())) {
                                    mTaskDetailsBean.setIsClick("0");
                                    mAdapter.notifyDataSetChanged();

                                    //点击
                                    favoriteOperation("O");
                                }

                                List<String> businessIdList = mTaskDetailsBean.getBusinessIds();

                                if ("1".equals(mTaskDetailsBean.getNeedBindBusinessId()) && (businessIdList != null && businessIdList.size() > 1)) {
                                    //进入需要选择业务单位
                                    final List<String> functionUnitIdList = new ArrayList<>();
                                    List<String> functionUnitNameList = new ArrayList<>();

                                    if (businessDetailsList != null && businessIdList != null) {
                                        for (CardDeskFunctionResponseBean.BusinessBean businessBean : businessDetailsList) {
                                            for (String businessId : businessIdList) {
                                                if (TextUtils.equals(businessId, businessBean.getBuId())) {
                                                    functionUnitIdList.add(businessBean.getBuId());
                                                    functionUnitNameList.add(businessBean.getBuName());
                                                }
                                            }
                                        }
                                    }

                                    new ChoosePickerDialog.Builder(mActivity).setData(functionUnitNameList).setTitle(getString(R.string.choose_business_unit)).setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
                                        @Override
                                        public void onSelected(String itemValue, int position) {
                                            mTaskDetailsBean.setBusinessId(functionUnitIdList.get(position));

                                            String taskType = mTaskDetailsBean.getTaskType();

                                            Bundle bundle = new Bundle();
                                            bundle.putSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS, mTaskDetailsBean);

                                            TaskRouterUtils.goFunction((BaseCardDeskActivity) mActivity, taskType, bundle);
                                        }

                                        @Override
                                        public void onCancel() {

                                        }
                                    }).create().show();
                                } else {
                                    //直接进入功能卡片中的具体业务
                                    mTaskDetailsBean.setBusinessId(businessIdList.get(0));

                                    String taskType = mTaskDetailsBean.getTaskType();

                                    Bundle bundle = new Bundle();
                                    bundle.putSerializable(Constant.KEY_CARD_DESK_FUNCTION_DETAILS, mTaskDetailsBean);

                                    TaskRouterUtils.goFunction((BaseCardDeskActivity) mActivity, taskType, bundle);
                                }
                            }
                        });
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), false);
                        mStateLayout.setSystemListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mStateLayout.showProgressView(false);

                                getFunctionInfo();
                            }
                        });
                    }
                    break;
                case REQUEST_OPERATION_FAVORITE:
                    if ("0".equals(commonClass.getCode())) {
                        if ("F".equals(mType)) {
                            mTaskDetailsBean.setIsCollect("1");
                            toast(getString(R.string.favorite_success));
                        } else if ("O".equals(mType)) {

                        }
                    } else {
                        toast(commonClass.getMsg());
                    }
                    break;
                default:
                    break;
            }
        }

        @Override
        public void onFailed(String result, int what) {
            mStateLayout.showNetworkView(false);
            mStateLayout.setNetworkListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mStateLayout.showProgressView(false);

                    getFunctionInfo();
                }
            });
        }

        @Override
        public void onFinish(int what) {
            mStateLayout.showContentView();

            dismissProgressDialog();
        }
    };
}
